#include <iostream>
#include <gmp.h>
#include "SHA1.h"
#include "DSA.h"

using namespace std;

int main() {
    string str = SHA1("ZhaoLulu");
    cout << "字符串SHA1值：" << str << endl;
    char sha[40];
    strcpy(sha, str.c_str());
    mpz_t M;
    mpz_init(M);
    mpz_set_str(M, sha, 40);

    mpz_t p;
    mpz_t q;
    mpz_t g;
    mpz_init(p);
    mpz_init(q);
    mpz_init(g);
    global_components(p, q, g);
    gmp_printf("p: %Zd\n", p);
    gmp_printf("q: %Zd\n", q);
    gmp_printf("g: %Zd\n", g);

    mpz_t x;
    mpz_t y;
    mpz_t k;
    mpz_init(x);
    mpz_init(y);
    mpz_init(k);
    private_key(q, x);
    public_key(g, x, p, y);
    secret_number(q, k);
    cout << "私钥";
    gmp_printf("x: %Zd\n", x);
    cout << "公钥";
    gmp_printf("y: %Zd\n", y);
    cout << "秘密随机数";
    gmp_printf("k: %Zd\n", k);

    FILE *fp = fopen("dsa_key.txt", "w+");
    mpz_out_str(fp, 16, y);
    fclose(fp);

    mpz_t r, s;
    mpz_init(r);
    mpz_init(s);
    dsa_sign(r, s, p, q, g, k, x, M);
    cout << "签名：";
    gmp_printf("(%Zd,%Zd)\n", r, s);

    fp = fopen("signature1.txt", "w+");
    mpz_out_str(fp, 16, r);
    fclose(fp);
    fp = fopen("signature2.txt", "w+");
    mpz_out_str(fp, 16, s);
    fclose(fp);

    mpz_t key;
    mpz_init(key);
    fp = fopen("dsa_key.txt", "r");
    mpz_inp_str(key, fp, 16);
    fclose(fp);

    mpz_t r1;
    mpz_t s1;
    mpz_init(r1);
    mpz_init(s1);
    fp = fopen("signature1.txt", "r");
    mpz_inp_str(r1, fp, 16);
    fclose(fp);
    fp = fopen("signature2.txt", "r");
    mpz_inp_str(s1, fp, 16);
    fclose(fp);

    if (dsa_verify(r1, s1, p, q, g, key, M)) {
        cout << "验证成功！" << endl;
    }
}
